<template>
<div class="tcftofactory">
  <div>
    <el-breadcrumb @click="specialInitialProcess" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/initiatingprocess' }" v-if="isShowItem">{{process[processNumber]}}</el-breadcrumb-item>
      <span @click.stop=";" v-if="isShowSpan">{{process[processNumber]}} <i class="el-icon-arrow-right"></i> </span>
      <span @click.stop=";">TCF付定金给工厂</span>
    </el-breadcrumb>
  </div>

  <div class="tcftofactory-top">
    <h2>定金付款申请单</h2>

    <div class="head">
      <div class="btns clearfix">
        <el-button class="bind" v-show="!editable" type="primary" :disabled="!editable2" @click="bindOrder">绑定订单</el-button>


        <!-- <el-button v-if="editable" class="export" :disabled="!editable2" type="primary">导出</el-button> -->
        <!-- <el-button v-else  class="export" :disabled="true" type="primary">导出</el-button> -->

      </div>

      <div class="select-orders ">
        <el-row :gutter="20">
          <el-col :span="10">
            <div>
              <p class="select-orders-line">
                选中的外贸订单
              <el-button v-show="editable ? editable2 : false"  @click="bindOrder" type="text">点击修改</el-button></p>
              <ul>
                <li><a href="#">{{saveData.tcftofactory_bindFContracts[0]}}</a></li>
              </ul>
            </div>
          </el-col>
          <el-col :span="10" :offset="4">
            <div>
              <p class="select-orders-line">选中的内贸订单</p>
              <ul>
                <!-- <li v-for="item in saveData.tcftofactory_bindDContracts">
                <a href="#">{{item}}</a>
                </li> -->

                <li>
                  <a href="#">{{saveData.tcftofactory_bindDContracts[0]}}</a>
                </li>
              </ul>
            </div>
          </el-col>
        </el-row>
      </div>

      <div class="tcf-table">
        <h2>天津金贸链进出口有限公司</h2>
        <h2>付款申请单</h2>

        <div class="tcf-table-wrap">
          <el-row>
            <el-col :span="4"><span>申请人</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2: true" v-model="saveData.tcftofactory_applicant" placeholder="流程发起人"></el-input></span></el-col>
            <el-col :span="4"><span>申请日期</span></el-col>
            <el-col :span="8">
              <span>
              <el-date-picker  :readonly="editable ? !editable2 : true"  @change="mustUpdate2"
              v-model="tcftofactory_applicationDate"
              format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"
              type="date"
              placeholder="选择日期">
            </el-date-picker>
          </span>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>申请部门</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_applicationDepart" placeholder="申请部门"></el-input></span></el-col>
            <el-col :span="4"><span>付款方式</span></el-col>
            <el-col :span="8">
              <el-row>
                <el-col :span="6" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true":value="'0'" @click="checkBoxRadio('selPayMethods', $event)" v-model="tcftofactory_checkedPayMethods">
                  <span>支票</span>
                </el-col>
                <el-col :span="10" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true" :value="'1'" @click="checkBoxRadio('selPayMethods', $event)" v-model="tcftofactory_checkedPayMethods">
                  <span>银行付款</span>
                </el-col>
                <el-col :span="8" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true" :value="'2'" @click="checkBoxRadio('selPayMethods', $event)" v-model="tcftofactory_checkedPayMethods">
                  <span>其他</span>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row class="tcf-table-title">
            <el-col class="tcf-table-title-left" :span="12">付款方信息</el-col>
            <el-col class="tcf-table-title-right" :span="12">收款方信息</el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>付款公司名称</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2 : true" placeholder="" v-model="saveData.tcftofactory_payCompany"></el-input></span></el-col>
            <el-col :span="4"><span>收款公司名称</span></el-col>
            <el-col :span="8"><span><el-input placeholder="请输入收款公司" :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_collectionCompany"> </el-input></span></el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>付款开户银行</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2 : true"  placeholder="" v-model="saveData.tcftofactory_payBank"></el-input></span></el-col>
            <el-col :span="4"><span>收款开户银行</span></el-col>
            <el-col :span="8"><span><el-input placeholder="请输入收款开户银行" :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_collectionBank" ></el-input></span></el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>付款银行账号</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2 : true" placeholder="" v-model="saveData.tcftofactory_payAccount"></el-input></span></el-col>
            <el-col :span="4"><span>收款银行账号</span></el-col>
            <el-col :span="8"><span><el-input placeholder="请输入收款开户银行账号" :readonly="editable ? !editable2 : true" type="number" v-model="saveData.tcftofactory_collectionAccount" ></el-input></span></el-col>
          </el-row>

          <el-row>
            <el-col :span="16">
              <el-row>
                <el-col :span="6" class="no-border"><span>付款金额大写(人民币):</span></el-col>
                <el-col :span="18" class="tcf-table-noright">
                  <el-input :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_paymentBigAmount"></el-input>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="8">
              <el-row>
                <el-col :span="6" class="no-border"><span>金额小写(￥):</span></el-col>
                <el-col :span="18" class="tcf-table-noright">
                  <el-input :readonly="editable ? !editable2 : true" type="number" v-model="saveData.tcftofactory_paymentAmount"></el-input>
                </el-col>
              </el-row>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>付款摘要</span></el-col>
            <el-col :span="20">
              <el-input :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_paymentAbstract"></el-input>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>内贸合同编号</span></el-col>
            <el-col :span="5">
              <el-input :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_dtcNO"></el-input>
            </el-col>
            <el-col :span="3"><span>业务类型</span></el-col>
            <el-col :span="4">
              <el-select @change="mustUpdate" :disabled="editable ? !editable2 : true"  v-model="saveData.tcftofactory_businessType">
                <el-option v-for="(item,index) in tcftofactory_businessTypeoptions" :key="index" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="3"><span>签订日期</span></el-col>
            <el-col :span="5">
              <el-date-picker format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd"  @change="mustUpdate2" :readonly="editable ? !editable2 : true" v-model="tcftofactory_signDate" type="date">
              </el-date-picker>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="4"><span>合同总额</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2 : true"  type="number"  v-model="saveData.tcftofactory_contractAmount"></el-input></span></el-col>
            <el-col :span="4"><span>已付款金额</span></el-col>
            <el-col :span="8"><span><el-input :readonly="editable ? !editable2 : true" type="number" v-model="saveData.tcftofactory_payedMount"></el-input></span></el-col>
          </el-row>


          <el-row>
            <el-col :span="4"><span>本次付款金额</span></el-col>
            <el-col :span="5">
              <el-input type="number" :readonly="!editable" v-model="saveData.tcftofactory_thisPaymentAmount"></el-input>
            </el-col>
            <el-col :span="3" class="special-row">
              <el-row>
                <el-col :span="24" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true"  :value="0" @click="checkBoxRadio('thisPaymentType', $event)" v-model="tcftofactory_thisPaymentTypes">
                  <span>赊销款</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true" :value="1" @click="checkBoxRadio('thisPaymentType', $event)" v-model="tcftofactory_thisPaymentTypes">
                  <span>垫税款</span>
                </el-col>
              </el-row>
            </el-col>

            <el-col :span="4"><span>未付款金额</span></el-col>
            <el-col :span="5">
              <el-input type="number" :readonly="editable ? !editable2 : true" v-model="saveData.tcftofactory_nonPaymentAmount"></el-input>
            </el-col>
            <el-col :span="3" class="special-row">
              <el-row>
                <el-col :span="24" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true" :value="0" @click="checkBoxRadio('nonPaymentType', $event)" v-model="tcftofactory_nonPaymentTypes">
                  <span>赊销款</span>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" class="no-border">
                  <input type="checkbox" :disabled="editable ? !editable2 : true" :value="1" @click="checkBoxRadio('nonPaymentType', $event)" v-model="tcftofactory_nonPaymentTypes">
                  <span>垫税款</span>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </div>

      </div>

    </div>


    <div class="upload">
      <p class="upload-hint">票据/附件</p>
      <div>
        <div class="upload-btn">
          <input type="file"  v-show="editable ? editable2 : false"  name="file" multiple @change="selectFiles">
          <el-button v-if="editable" type="primary" :disabled="!editable2">选择附件</el-button>
          <el-button v-else type="primary" :disabled="true">选择附件</el-button>
        </div>

        <ul class="upload-files">
          <li @mouseover="handleOver(item)"   @mouseout="handleOut(item)" v-for="(item,index) in saveData.attachedFiles" :key="index">
            <span @click="download(item.id, $event)">{{item.name}}</span>
            <span v-if="editable && item.status" class="el-icon-circle-check" style="color:#67c23a;"></span>
            <span v-else-if="editable" class="el-icon-circle-close" @click="changeFiles(index,item)" style="color:red;"></span>
          </li>
        </ul>
      </div>
    </div>

    <div class="bind-window">
      <el-dialog title="订单绑定" width="70%" :visible.sync="dialogCtrl.outerVisible">

        <el-form :inline="true">
          <el-form-item label="订单编号">
            <el-input v-model="orderNumber" placeholder="请输入订单编号"></el-input>
          </el-form-item>
          <el-form-item label="外贸合同号">
            <el-input v-model="foreignTradeContractNumber" placeholder="请输入外贸合同号"></el-input>
          </el-form-item>

          <el-form-item label="买家名称">
            <el-input v-model="buyerName" placeholder="请输入买家名称"></el-input>
          </el-form-item>

          <el-form-item>
            <el-date-picker
            v-model="orangeDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOrange">
          </el-date-picker>
        </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="queryFtc(-1)">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="table1Data" style="width: 100%" border>
          <el-table-column prop="table1_orderNumber" label="订单编号" sortable width="240" :sort-method="table1Sort">
            <template slot-scope="scope">
            <span>
              <input type="checkbox" :value="scope.row.table1_id" @click="checkBoxRadio('selForder', $event)" v-model="tcftofactory_selectOrder">
              <span>{{scope.row.table1_orderNumber}}</span>
            </span>
          </template>
          </el-table-column>

          <el-table-column prop="table1_ftcNumber" label="外贸合同号" sortable>
          </el-table-column>
          <el-table-column prop="table1_createTime" label="订单生成时间" >
          </el-table-column>

          <el-table-column prop="table1_buyerName" label="买家名称" >
          </el-table-column>



          <el-table-column prop="table1_orderProcess" label="订单流程" >
          </el-table-column>

          <el-table-column prop="table1_orderStatus" label="订单状态" >
          </el-table-column>
        </el-table>


        <div class="pageing">
          <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.currPage"
          :page-sizes="[20, 30, 50, 100]"
          :page-size="page.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalSize">
        </el-pagination>

      </div>

        <el-dialog width="50%" title="内贸合同绑定" :visible.sync="dialogCtrl.innerVisible" append-to-body>

          <el-table v-loading="loading" :data="table2Data" style="width: 100%" border>
            <el-table-column prop="table2_dtcNumber" label="内贸合同编号" width="200">
              <template slot-scope="scope">
              <span>
                <input type="checkbox"  @click="checkBoxRadio('selDorder', $event)" :value="scope.row.table2_id"  v-model="tcftofactory_selectOrder2">
                <span>{{scope.row.table2_dtcNumber}}</span>
              </span>
            </template>
            </el-table-column>

            <el-table-column prop="table2_sellerName" label="供方名称">
            </el-table-column>

            <el-table-column prop="table2_contractAmount" label="合同金额">
            </el-table-column>
          </el-table>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" :disabled="canNotSelect2" @click="bindInnerConfirm">确定</el-button>
            <el-button @click="bindInnerCancel">取 消</el-button>
          </div>
        </el-dialog>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" :disabled="canNotSelect" @click="bindOuterSelect">选择内贸合同</el-button>
          <el-button @click="bindOuterCancel">取 消</el-button>
        </div>

      </el-dialog>
    </div>


  </div>


  <div class="tcftofactory-bottom">
    <fixed-form v-if="editable" ref="fixedForm" :saveAndSend="saveAndSend" :editable="editable2" :saveData="saveData" :sendMenus="sendMenus" processName="tcftofactory" />
    <fixed-form  v-else ref="fixedForm" :saveAndSend="false" :editable="false" :saveData="saveData" :sendMenus="sendMenus" processName="tcftofactory" />
  </div>

</div>
</template>

<script>
import fixedForm from '../common/fixedForm';
import {
  uploadFiles,
  getSendMenus,
  getData,
  queryBindContracts,
  queryBindDtcContracts
} from '@/server/initiatingprocess';
import {
  getStore
} from '@/assets/js/common'

import {filedownload , deleteFile} from '@/server/customermanagement/index.js'

export default {

  beforeRouteEnter(to, from, next) {
    let dom = document.querySelector('.initiatingprocess  .routers-ctrl');
    if (dom) {
      dom.style.zIndex = '-1';
    }

    next(vm => {
      //说明从其他位置跳到该流程中
      if (to.query.dTab) {

        vm.processNumber = parseInt(to.query.itemStatus);

        if (to.query.isHive == 1) {
          vm.$store.commit('tcftofactory/SET_SAVE');
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName,
            isHive: 1,
          }).then((response) => {

            let data = response.data.datas[0];

            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {

                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              // if (k === 'relationFormInstId') {
              //   if (_.isString(v)){
              //     return v.split(',');
              //   } else {
              //     return [];
              //   }
              // }

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }


              if ((k == 'tcftofactory_checkedPayMethods') || ( k == 'tcftofactory_thisPaymentTypes') || (k == 'tcftofactory_nonPaymentTypes')) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });

            _.extend(vm.saveData, data);
            vm.editable = true;

            let approvalIndex, approvalFullName, names = [];

            if (data.role) {
              vm.editable2 = data.role.DEFAULT == 'W' ? true : false;
              vm.saveAndSend = vm.editable2;

              let copyApprovals = _.cloneDeep(data.approvals);


              for (let i = 0; i < copyApprovals.length ; i++) {
                for (var prop in vm.saveData.originApprovals[i]) {
                  if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                    vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                  }
                }
              }

              vm.tcftofactory_applicationDate =  vm.saveData.tcftofactory_applicationDate ;
              vm.tcftofactory_signDate =  vm.saveData.tcftofactory_signDate;
              vm.tcftofactory_checkedPayMethods = _.cloneDeep(vm.saveData.tcftofactory_checkedPayMethods);
              vm.tcftofactory_nonPaymentTypes = _.cloneDeep(vm.saveData.tcftofactory_nonPaymentTypes);
              vm.tcftofactory_thisPaymentTypes = _.cloneDeep(vm.saveData.tcftofactory_thisPaymentTypes);

              vm.saveData.isSalesMan = false;

            } else {
              vm.saveData.isSalesMan = true;
            }


            getSendMenus({
              flowId: to.query.flowId,
              currNodeId: to.query.currNodeId
            }).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();

            });

          });
        } else {
          getData({
            formInstId: to.query.formInstId,
            formServiceName: to.query.formServiceName

          }).then((response) => {

            let data = response.data.datas[0];

            //对其中的字符串类型的附件名称，进行分割
            data = JSON.parse(JSON.stringify(data).replace(/(attachedFiles)/g, function(){return 'useless01';}).replace(/(attachedFileList)/g, function() {
              return "attachedFiles";
            }).replace(/(relationFormInst)/g, function(){ return 'relationFormInstId'}), function(k, v) {
              if (k === 'attachedFiles') {

                if (_.isArray(v)) {
                  return v.map((e) => {
                    return {
                      name: e.realFileName,
                      status: 1,
                      id: e.id
                    };
                  });
                } else {
                  return [];
                }
              }
              // if (k === 'relationFormInstId') {
              //   if (_.isString(v)){
              //     return v.split(',');
              //   } else {
              //     return [];
              //   }
              // }

              if (k === 'relationFormInstId'){
                if (_.isPlainObject(v)){
                  return [v];
                } else {
                  return [];
                }
              }

              if ((k.indexOf("_bindFContracts") != -1) || (k.indexOf("_bindDContracts") != -1)) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }

              if ((k == 'tcftofactory_checkedPayMethods') || ( k == 'tcftofactory_thisPaymentTypes') || (k == 'tcftofactory_nonPaymentTypes')) {
                if (_.isString(v)){
                  return v.split(',');
                } else {
                  return [];
                }
              }
              return v;
            });

            _.extend(vm.saveData, data);
            vm.editable = true;

            let approvalIndex, approvalFullName, names = [];

            if (data.role) {
              data.role.forEach((e) => {
                if (e.itemName.indexOf("item") === -1) {
                  vm.saveData.roles[e.itemName] = e.permission;
                } else {
                  let num = Number(e.itemName[e.itemName.length - 1]) - 1;
                  if (e.permission == 'W') {
                    approvalIndex = num;
                    approvalFullName = e.itemName;
                  }
                }
              });

              vm.editable2 = (vm.saveData.roles.tcftofactory_applicant == 'W') ? true : false;
              vm.saveAndSend = true;


              let copyApprovals = _.cloneDeep(data.approvals);


              if (approvalIndex !== undefined) {
                if (approvalIndex >= 0) {
                  for (let i = 0; i <= approvalIndex; i++) {
                    if (copyApprovals[i]){
                      for (var prop in vm.saveData.originApprovals[i]) {
                        if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                          vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                        }
                      }
                      vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                    }
                  }
                }

                let date = new Date();
                vm.saveData.originApprovals[approvalIndex].rw = 'W';
                vm.saveData.originApprovals[approvalIndex].approval_time = date.toLocaleDateString() + ' ' + date.toTimeString().slice(0, 9);
                vm.saveData.originApprovals[approvalIndex].approval_username = JSON.parse(getStore('userMsg')).userName;;

              }  else if (copyApprovals.length > 0){
                for (let i = 0; i < copyApprovals.length; i++) {

                  for (var prop in vm.saveData.originApprovals[i]) {
                    if ((prop != 'rw') && (prop != 'approval_div_name') && (prop != 'item')){
                      vm.saveData.originApprovals[i][prop] = copyApprovals[i][prop]
                    }
                  }
                  vm.saveData.originApprovals[i].approval_id = '' + copyApprovals[i].id;
                }
              }


              vm.tcftofactory_applicationDate =  vm.saveData.tcftofactory_applicationDate ;
              vm.tcftofactory_signDate =  vm.saveData.tcftofactory_signDate;
              vm.tcftofactory_checkedPayMethods = _.cloneDeep(vm.saveData.tcftofactory_checkedPayMethods);
              vm.tcftofactory_nonPaymentTypes = _.cloneDeep(vm.saveData.tcftofactory_nonPaymentTypes);
              vm.tcftofactory_thisPaymentTypes = _.cloneDeep(vm.saveData.tcftofactory_thisPaymentTypes);

              vm.saveData.isSalesMan = false;

            } else {
              vm.saveData.isSalesMan = true;
            }


            getSendMenus({
              flowId: to.query.flowId,
              currNodeId: to.query.currNodeId
            }).then((response) => {
              vm.sendMenus = response.data.datas[0];
              vm.$forceUpdate();
              vm.$refs.fixedForm.isForceUpdate = true;
              vm.$refs.fixedForm.$forceUpdate();

            });

          });
        }
      } else {
        vm.$message({
          message: '请先绑定订单，否则无法保存和发送',
          type: 'warning',
          duration: 3000,
          showClose: true
        });
      }
    });
  },
  beforeRouteLeave(to, from, next){
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';
    if (!this.$store.state.tcftofactory.hasSaved){
      this.$confirm('您填写的内容尚未保存或发送,是否要离开?', '提示', {
        confirmButtonText: '离开',
        cancelButtonText: '留下',
        type: 'warning'
      }).then(() => {
        next();
      }).catch(() => {
        Array.prototype.forEach.call(document.getElementsByTagName('*'), (e) => {
          e.blur();
        });
        next(false);
      });
    } else {
      next();
    }
  },
  created() {
    let state = _.cloneDeep(this.$store.state.tcftofactory);

    this.saveData = {
      roles: {}
    }, this.sendMenus = [];

    for (var prop in state) {
      this.saveData[prop] = state[prop];
    }

  },
  mounted() {

    //刷新浏览器时，避免重叠
    document.querySelector('.initiatingprocess  .routers-ctrl').style.zIndex = '-1';



    let that = this;
    let closeDom = document.querySelectorAll('.bind-window i.el-dialog__close.el-icon-close');
    for (let i = 0; i < closeDom.length; i++) {
      closeDom[i].onclick = function() {
        that.bindInnerCancel();
      };
    }


    getSendMenus({
      'flowId': 3
    }).then((response) => {
      this.sendMenus = response.data.datas[0];
      this.$forceUpdate();
    });

    //判断面包屑二级路由是否可退回
    let isCreatFlow = getStore('isCreatFlow');
    this.isShowItem = !isCreatFlow ? false : true;
    this.isShowSpan = !isCreatFlow ? true : false;

    this.saveData.tcftofactory_applicant = JSON.parse(getStore("userMsg")).userName;
    this.saveData.tcftofactory_applicationDepart = JSON.parse(getStore("userMsg")).orgName;

  },
  updated() {},
  methods: {
    specialInitialProcess() {
      let cls = event.target.classList;
      if (cls.contains("el-icon-arrow-right") && cls.contains("el-breadcrumb__separator")) return;

      let dom = document.querySelector('.initiatingprocess .routers-ctrl');
      if (dom) {
        dom.style.zIndex = '0';
      }
    },
    mustUpdate() {
      this.$forceUpdate();
    },

    mustUpdate2() {
      this.saveData.tcftofactory_applicationDate  = this.tcftofactory_applicationDate;
      this.saveData.tcftofactory_signDate  = this.tcftofactory_signDate;
      this.$forceUpdate();
    },
    bindOrder() {
      this.dialogCtrl.outerVisible = true;
      this.canNotSelect = true;
      this.canNotSelect2 = true;
      this.tcftofactory_bindFContracts = [];
      this.tcftofactory_bindDContracts = [];

      this.orderNumber = '';
      this.foreignTradeContractNumber = '';
      this.buyerName = '';
      this.queryFtc(1, 30);
    },

    handleSizeChange(size){
      this.page.pageSize = size;
      //需要重新查询
      this.queryFtc(1, this.page.pageSize);
    },
    handleCurrentChange(currPage){
      this.page.currPage = currPage;
      //需要重新查询
      this.queryFtc(this.page.currPage, this.page.pageSize);
    },
    queryFtc(currPage, pageSize) {
      //通过查询来获得外贸合同订单，并修改table1的数据来进行显示

      let startTime, endTime;
      if (currPage ==  -1){
        currPage = 1;
        this.page.currPage = 1;
        pageSize = this.page.pageSize;
      }

      this.loading = true;
      this.table1Data = [];
      this.table2Data = [];
      this.tcftofactory_selectOrder = [];
      this.tcftofactory_selectOrder2 = [];

      if (this.orangeDate) {
        startTime = new Date('' + this.orangeDate[0]).getTime();
        endTime = new Date('' + this.orangeDate[1]).getTime();
        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize,
          gt_createTime: startTime,
          lt_createTime: endTime
        }).then((response) => {

          this.loading = false;
          this.page.totalSize = response.data.totalSize;
          this.queryOrderData = response.data.datas;

          let table1Data = this.table1Data;
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;


            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }

          this.$forceUpdate();
        });
      } else {
        queryBindContracts({
          flowId: 1,
          orderCode: this.orderNumber,
          ftcCode: this.foreignTradeContractNumber,
          buyerName: this.buyerName,
          currPage: currPage - 1,
          pageSize: pageSize
        }).then((response) => {

          this.loading = false;
          this.page.totalSize = response.data.totalSize;
          this.queryOrderData = response.data.datas;

          let table1Data = this.table1Data;
          for (let i = 0; i < this.queryOrderData.length; i++) {

            if (!table1Data[i]) {
              table1Data[i] = {};
            }
            table1Data[i].table1_orderNumber = this.queryOrderData[i].orderCode;
            table1Data[i].table1_ftcNumber = this.queryOrderData[i].ftcCode;
            table1Data[i].table1_buyerName = this.queryOrderData[i].buyerName;
            table1Data[i].table1_id = this.queryOrderData[i].id;


            let date = new Date(this.queryOrderData[i].createTime);
            let m = date.getMonth() + 1;
            m = m < 10 ? '0' + m  : m;
            let d = date.getDate();
            d = d < 10 ? '0' + d  : d;

            table1Data[i].table1_createTime = date.getFullYear() + '-' + m + '-' + d;

            switch(this.queryOrderData[i].formInstStatus){
              case 0:
              case 1:
              table1Data[i].table1_orderStatus = '流转中';
              break;
              case 2:
              table1Data[i].table1_orderStatus = '完结';
              break;
            }

            table1Data[i].table1_orderProcess = this.queryOrderData[i].flowName;
          }

          this.$forceUpdate();
        });
      }
    },
    table1Sort(a, b) {
      let a1 = a.toString().slice(a.length - 5);
      let b1 = b.toString().slice(b.length - 5);
      return parseInt(b) - parseInt(b);
    },
    checkBoxRadio(type, event) {
      let value = event.target.value;

      if (type === 'selForder') {

        if (value === this.tcftofactory_selectOrder[0]) {
          this.canNotSelect = true;
        } else {
          this.canNotSelect = false;
        }

        this.tcftofactory_selectOrder = [value];

        this.showftc = this.queryOrderData.find((e) => {
          return e.id == this.tcftofactory_selectOrder[0]
        });

        this.tcftofactory_bindFContracts[0] = this.showftc.ftcCode;

      } else if (type === 'selDorder') {

        if (value === this.tcftofactory_selectOrder2[0]) {
          this.canNotSelect2 = true;
        } else {
          this.canNotSelect2 = false;
        }
        this.tcftofactory_selectOrder2 = [value];

        let currDtc = this.queryOrderData2.find(e => {
          return e.id == this.tcftofactory_selectOrder2[0];
        });

        this.tcftofactory_bindDContracts[0] = currDtc.bd_no;

      } else if (type === 'selPayMethods') {
        this.tcftofactory_checkedPayMethods = [value];
        this.saveData.tcftofactory_checkedPayMethods = [value]
      } else if (type === 'thisPaymentType') {
        this.tcftofactory_thisPaymentTypes = [value];
        this.saveData.tcftofactory_thisPaymentTypes = [value];
      } else if (type === 'nonPaymentType') {
        this.tcftofactory_nonPaymentTypes = [value];
        this.saveData.tcftofactory_nonPaymentTypes = [value];
      }
    },
    bindOuterSelect() {
      let that = this;
      this.dialogCtrl.innerVisible = true;

      let closeDom = document.querySelectorAll('i.el-dialog__close.el-icon-close');
      for (let i = 0; i < closeDom.length; i++) {
        closeDom[i].onclick = function() {
          that.bindInnerCancel();
        };
      }

      /*
      需要根据当前选中的订单值即 checkedFOrder,来修改 table2Data，用于显示该订单下的内贸订单
      */
      //
      // this.showftc = this.queryOrderData.find((e) => {
      //   return e.ftcCode == this.tcftofactory_bindFContracts[0]
      // });

      this.saveData.orderCode = this.showftc.orderCode;
      this.saveData.buyerName = this.showftc.buyerName;

      //绑定的外贸和合同的id
      this.saveData.bindingFormInstId = this.showftc.id;
      this.loading = true;

      queryBindDtcContracts({
        formInstId: this.showftc.id
      }).then((response) => {
        this.loading = false;
        this.queryOrderData2 = response.data.datas;

        let table2Data = this.table2Data;

        for (let i = 0; i < this.queryOrderData2.length; i++) {

          if (!table2Data[i]) {
            table2Data[i] = {};
          }
          table2Data[i].table2_dtcNumber = this.queryOrderData2[i].bd_no;
          table2Data[i].table2_sellerName = this.queryOrderData2[i].bd_seller;
          table2Data[i].table2_contractAmount = this.queryOrderData2[i].bd_table1_totalAmount;
          table2Data[i].table2_id = this.queryOrderData2[i].id;
        }
        this.$forceUpdate();
      });
    },
    bindOuterCancel() {
      this.bindInnerCancel();
    },
    bindInnerConfirm() {
      this.dialogCtrl.outerVisible = false;
      this.dialogCtrl.innerVisible = false;

      if (this.tcftofactory_bindDContracts.length === 0) {
        this.bindInnerCancel();
        return;
      }

      this.saveData.tcftofactory_bindFContracts = _.cloneDeep(this.tcftofactory_bindFContracts);
      this.saveData.tcftofactory_bindDContracts = _.cloneDeep(this.tcftofactory_bindDContracts);
      this.editable = true;
      /*
       */

      // this.showdtcs = this.queryOrderData2.filter((e)=>{
      //    return this.saveData.tcftofactory_bindDContracts.indexOf(e.bd_no) != -1;
      // });

      this.showdtcs[0] = this.queryOrderData2.find((e) => {
        return e.bd_no == this.saveData.tcftofactory_bindDContracts[0];
      });


      this.saveData.tcftofactory_collectionCompany = this.showdtcs[0].bd_ch_name;
      this.saveData.tcftofactory_collectionBank = this.showdtcs[0].bd_ch_bankOfDeposit;
      this.saveData.tcftofactory_collectionAccount = this.showdtcs[0].bd_ch_account.replace(/(\s+)/g, '');
      this.saveData.tcftofactory_dtcNO = this.showdtcs[0].bd_no;
      this.saveData.tcftofactory_signDate = this.showdtcs[0].bd_date;
      this.tcftofactory_signDate = this.showdtcs[0].bd_date;

      /*
      this.saveData.tcftofactory_payCompany = this.showdtcs[0].bd_ch_name;
      this.saveData.tcftofactory_payBank = this.showdtcs[0].bd_ch_bankOfDeposit;
      this.saveData.tcftofactory_payAccount = this.showdtcs[0].bd_ch_account;
      */

      this.saveData.tcftofactory_payCompany = '天津金贸链进出口有限公司';
      this.saveData.tcftofactory_payBank = '中信银行股份有限公司天津自由贸易试验区分行';
      this.saveData.tcftofactory_payAccount = '8111401011700147295';

      let temp = this.showdtcs[0].bd_table1;
      if (temp != null){
        this.saveData.tcftofactory_contractAmount = temp[temp.length - 1] .bd_table1_lineAmount;
      }


      this.table1Data = [];
      this.table2Data = [];
      this.page.pageSize = 30;
      this.$forceUpdate();
    },
    bindInnerCancel() {

      this.dialogCtrl.outerVisible = false;
      this.dialogCtrl.innerVisible = false;
      this.tcftofactory_bindDContracts = [];
      this.tcftofactory_bindFContracts = [];
      this.canNotSelect = true;
      this.canNotSelect2 = true;
      this.table1Data = [];
      this.table2Data = [];
      this.tcftofactory_selectOrder = [];
      this.page.pageSize = 30;
      this.$forceUpdate();
    },
    selectFiles(event) {
      //票据附件
      let _this = this;


      //直接上传，并且获得后端返回的文件的url,将url保存到 this.data.attachedFiles中
      uploadFiles(event.target.files).then((resArr) => {
        resArr.forEach(function(res, i) {
          _this.saveData.attachedFiles.push({
            name: event.target.files[i].name,
            status: 1,
            id: res.data.datas[0].id
          });
        });

        _this.$forceUpdate();
      });
    },
    changeFiles(index,item) {
      deleteFile({'id':item.id}).then((res) => {
        if(res.code != 1 ){
          this.$message.error('删除失败，请检查网络后重试');
        } else {
          this.saveData.attachedFiles.splice(index, 1);
        }
      });
    },
    handleOver(item){
      item.status = 0;
      this.$forceUpdate();
    },
    handleOut(item){
      item.status = 1;
      this.$forceUpdate();
    },
    download(id, event){
      window.open('http://47.104.93.41/api/common/download?id='+id);
    },
  },
  data() {
    return {
      isShowItem: false,
      isShowSpan: false,
      editable: false, //未绑定订单时，表格不可编辑,
      editable2: true,
      saveAndSend: true,
      process: ['待发事项', '待办事项', '已办事项','发起流程'],
      processNumber: 3,
      tcftofactory_applicationDate: '',
      tcftofactory_signDate: '',
      page: {
        currPage: 1,
        pageSize: 30,
        totalSize: 0
      },
      dialogCtrl: {
        outerVisible: false,
        innerVisible: false,
      },
      loading: false,
      tcftofactory_selectOrder: [],
      tcftofactory_selectOrder2: [],
      tcftofactory_bindFContracts: [], //控制绑定订单时的外贸合同单选显示
      tcftofactory_bindDContracts: [],
      tcftofactory_checkedPayMethods: [],
      tcftofactory_thisPaymentTypes: [],
      tcftofactory_nonPaymentTypes: [],
      tcftofactory_businessTypeoptions: ['垫税', 'O/A', '代理'],
      canNotSelect: true,
      canNotSelect2: true,
      orderNumber: '',
      foreignTradeContractNumber: '',
      buyerName: '',
      queryOrderData: null,
      queryOrderData2: null,
      showftc: null,
      showdtcs: [],
      table1Data: [],
      table2Data: [],
      orangeDate: '',
      pickerOrange:{
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }]
        }
    }
  },
  props: {
    formIdStart: {
      type: String,
      required: true
    }
  },
  components: {
    fixedForm
  }
}
</script>

<style lang="scss">
body {
    .dialog-footer {
        text-align: center;
        button {
            margin-right: 50px;
        }
    }
}

.tcftofactory {
    padding: 20px;

    font-size: 15px;

    i.el-breadcrumb__separator {
        margin: 0 !important;
    }

    i.el-breadcrumb__separator[class*=icon] {
        margin: 0 !important;
        padding: 0 9px !important;
    }

    .tcftofactory-top {
        border: 1px solid #999;

        > h2 {
            text-align: center;
            padding: 20px;
        }

        a {
            color: #409EFF;
        }

        .head {
            padding: 0px 20px;
            position: relative;

            .tcf-table {
                h2 {
                    text-align: center;
                    padding: 10px 0;
                }

                .tcf-table-wrap {
                    border-left: 1px solid #999;
                    border-top: 1px solid #999;
                }

                .tcf-table-title {
                    text-align: center;

                    .tcf-table-title-left {
                        position: relative;
                        left: -1px;
                    }
                }

                .tcf-table-noright {
                    border-right: none !important;
                }

                .el-date-editor {
                    width: 100%;
                }

                .el-col {
                    height: 50px;
                    line-height: 50px;
                    padding-left: 5px;

                    border-right: 1px solid #999;
                    border-bottom: 1px solid #999;
                }

                .no-border {
                    border: none !important;
                }

                .special-row {
                    .el-col {
                        height: 25px;
                        line-height: 25px;
                    }
                }

                .el-input__inner {
                    border: none;
                }
            }

            .btns {
              position: absolute;
              top: -44px;

                .bind {
                    float: left;
                }
                .export {
                    float: right;
                }
            }

            .select-orders {

                padding: 10px 0;

                li {
                    padding: 5px 0;
                }
                .select-orders-line {
                  height: 40px;
                  line-height: 40px;
                }
            }

        }

        .bind-window {
            .el-form--inline .el-form-item {
                margin-right: 15px;
            }

            td {
                border: 1px solid #e6ebf5;
            }

            td:not(.el-table_1_column_1) {
                width: 120px;
                min-width: 120px;
            }

            .dialog-footer {
                text-align: center;
                button {
                    margin-right: 80px;
                }
            }

            a {
                color: #409EFF;
            }

        }

        .upload {
            padding: 20px;
            > div {
                border: 1px solid #999;
                padding: 20px 0 40px 20px;
            }

            .upload-btn {
                position: relative;
                > input {
                    opacity: 0;
                    width: 100px;
                    height: 40px;
                    position: absolute;
                    top: 0;
                    left: 0;
                }
            }

            .upload-files {

                > li {
                    width: 300px;
                    padding: 10px 0;
                    transition: all 0.5s linear;

                    &:hover {

                      >span {
                        color: #409EFF;
                      }
                    }
                  }

                font-size: 16px;
                span {
                    padding: 0 10px;
                    cursor: pointer;
                    display: inline;
                }
                span.el-icon-close:hover {
                    cursor: pointer;
                }
            }
            .upload-hint {
                font-size: 20px;
                margin-bottom: 10px;
            }
        }
    }

    .tcftofactory-bottom {
        border: 1px solid #999;
        margin-top: 20px;
    }
}
</style>
